package com.company.pangu.aliyun.risk.client;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanResultsRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.company.nuwa.common.utils.JsonUtils;
import com.company.pangu.aliyun.risk.config.RiskControlConfig;
import com.company.pangu.aliyun.risk.request.RiskImageSyncScanRequest;
import com.company.pangu.aliyun.risk.request.RiskTextScanRequest;
import com.company.pangu.aliyun.risk.request.RiskVideoAsyncScanRequest;
import com.company.pangu.aliyun.risk.response.RiskImageSyncScanResponse;
import com.company.pangu.aliyun.risk.response.RiskTextScanResponse;
import com.company.pangu.aliyun.risk.response.RiskVideoAsyncScanResponse;
import com.company.pangu.aliyun.risk.response.RiskVideoAsyncScanResultsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * <p>阿里云内容安全</p >
 *
 * @author Nikola Tesla
 * @version 1.0
 * @date 2020/09/25 11:48
 */
@Slf4j
public class RiskControlClient {

    private final IAcsClient riskControlAcsClient;

    public RiskControlClient(RiskControlConfig riskControlConfig) {
        IClientProfile profile = DefaultProfile.getProfile(
                riskControlConfig.getRegionId(),
                riskControlConfig.getAccessKeyId(),
                riskControlConfig.getAccessKeySecret()
        );
        this.riskControlAcsClient = new DefaultAcsClient(profile);
    }

    /**
     * 阿里云文本检测
     * <p>
     * https://help.aliyun.com/document_detail/70439.html?spm=a2c4g.11186623.6.701.5ebf4cactYviuu
     *
     * @param request
     * @return
     */
    public RiskTextScanResponse scanText(RiskTextScanRequest request) {
        TextScanRequest textScanRequest = new TextScanRequest();
        // 指定API返回格式。
        textScanRequest.setSysAcceptFormat(FormatType.JSON);
        textScanRequest.setHttpContent(StringUtils.getBytesUtf8(JsonUtils.objectToJson(request)), StandardCharsets.UTF_8.name(), FormatType.JSON);
        try {
            log.info("testScanText request={}", JsonUtils.objectToJson(request));
            HttpResponse httpResponse = riskControlAcsClient.doAction(textScanRequest);
            log.info("testScanText response={}", JsonUtils.objectToJson(httpResponse));
            // 服务端接收到请求，完成处理后返回的结果。
            if (Objects.nonNull(httpResponse) && httpResponse.isSuccess()) {
                return JsonUtils.jsonToObject(httpResponse.getHttpContentString(), RiskTextScanResponse.class);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        throw new RuntimeException("文本检测异常，请稍后再试~");
    }

    /**
     * 阿里云图片检测（同步）
     * <p>
     * https://help.aliyun.com/document_detail/50170.html?spm=a2c4g.11186623.6.744.6bfa4850Vjcw2P
     *
     * @param request
     * @return
     */
    public RiskImageSyncScanResponse syncScanImage(RiskImageSyncScanRequest request) {
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        // 指定API返回格式。
        imageSyncScanRequest.setSysAcceptFormat(FormatType.JSON);
        imageSyncScanRequest.setHttpContent(StringUtils.getBytesUtf8(JsonUtils.objectToJson(request)), StandardCharsets.UTF_8.name(), FormatType.JSON);
        try {
            log.info("syncScanImage request={}", JsonUtils.objectToJson(request));
            HttpResponse httpResponse = riskControlAcsClient.doAction(imageSyncScanRequest);
            log.info("syncScanImage response={}", JsonUtils.objectToJson(httpResponse));
            // 服务端接收到请求，完成处理后返回的结果。
            if (Objects.nonNull(httpResponse) && httpResponse.isSuccess()) {
                return JsonUtils.jsonToObject(httpResponse.getHttpContentString(), RiskImageSyncScanResponse.class);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        throw new RuntimeException("图片检测异常，请稍后再试~");
    }

    /**
     * 阿里云视频检测（异步）
     * https://help.aliyun.com/document_detail/70436.html?spm=a2c4g.11186623.6.689.5a234caccCfxOh
     *
     * @param request
     * @return
     */
    public RiskVideoAsyncScanResponse asyncScanVideo(RiskVideoAsyncScanRequest request) {
        VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
        // 指定API返回格式。
        videoAsyncScanRequest.setSysAcceptFormat(FormatType.JSON);
        videoAsyncScanRequest.setHttpContent(StringUtils.getBytesUtf8(JsonUtils.objectToJson(request)), StandardCharsets.UTF_8.name(), FormatType.JSON);
        try {
            log.info("asyncScanVideo request={}", JsonUtils.objectToJson(request));
            HttpResponse httpResponse = riskControlAcsClient.doAction(videoAsyncScanRequest);
            log.info("asyncScanVideo response={}", JsonUtils.objectToJson(httpResponse));
            // 服务端接收到请求，完成处理后返回的结果。
            if (Objects.nonNull(httpResponse) && httpResponse.isSuccess()) {
                return JsonUtils.jsonToObject(httpResponse.getHttpContentString(), RiskVideoAsyncScanResponse.class);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        throw new RuntimeException("视频检测异常，请稍后再试~");
    }

    /**
     * 阿里云视频检测(异步)，结果拉取
     * https://help.aliyun.com/document_detail/70436.html?spm=a2c4g.11186623.6.689.5a234caccCfxOh
     *
     * @param taskIds
     * @return
     */
    public RiskVideoAsyncScanResultsResponse asyncScanVideoResult(List<String> taskIds) {
        VideoAsyncScanResultsRequest videoAsyncScanResultsRequest = new VideoAsyncScanResultsRequest();
        // 指定API返回格式。
        videoAsyncScanResultsRequest.setSysAcceptFormat(FormatType.JSON);
        videoAsyncScanResultsRequest.setHttpContent(StringUtils.getBytesUtf8(JsonUtils.objectToJson(taskIds)), StandardCharsets.UTF_8.name(), FormatType.JSON);
        try {
            log.info("asyncScanVideoResult request={}", JsonUtils.objectToJson(taskIds));
            HttpResponse httpResponse = riskControlAcsClient.doAction(videoAsyncScanResultsRequest);
            log.info("asyncScanVideoResult response={}", JsonUtils.objectToJson(httpResponse));
            // 服务端接收到请求，完成处理后返回的结果。
            if (Objects.nonNull(httpResponse) && httpResponse.isSuccess()) {
                return JsonUtils.jsonToObject(httpResponse.getHttpContentString(), RiskVideoAsyncScanResultsResponse.class);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        throw new RuntimeException("视频检测结果拉取异常，请稍后再试~");
    }

    /**
     * shut down
     */
    public void shutdown() {
        if (Objects.nonNull(riskControlAcsClient)) {
            riskControlAcsClient.shutdown();
        }
    }

}
